package com.teamwhole.modules.act.service.ext;

import java.util.List;

import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.UserEntityManager;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.teamwhole.common.utils.SpringContextHolder;
import com.teamwhole.modules.act.utils.ActUtils;
import com.teamwhole.modules.sys.entity.Role;
import com.teamwhole.modules.sys.service.RoleService;
import com.teamwhole.modules.sys.service.UserService;

@Service
public class ActUserEntityService extends UserEntityManager {

	private UserService userService;

	private RoleService roleService;

	@Override
	public User findUserById(String userId) {
		return ActUtils.toActivitiUser(getUserService().findByLoginName(userId));
	}

	@Override
	public void deleteUser(String userId) {
		User user = findUserById(userId);
		if (user != null) {
			getUserService().delete(user.getId());
		}
	}

	@Override
	public List<Group> findGroupsByUser(String userId) {
		List<Group> list = Lists.newArrayList();
		for (Role role : getRoleService().findList(new Role(new com.teamwhole.modules.sys.entity.User(null, userId)))) {
			list.add(ActUtils.toActivitiGroup(role));
		}
		return list;
	}

	public UserService getUserService() {
		if (userService == null) {
			userService = SpringContextHolder.getBean(UserService.class);
		}
		return userService;
	}

	public RoleService getRoleService() {
		if (roleService == null) {
			roleService = SpringContextHolder.getBean(RoleService.class);
		}
		return roleService;
	}

}
